package com.blb.zycommunity.controller;

import com.blb.zycommunity.entity.ResponseResult;
import com.blb.zycommunity.entity.ZyOwner;
import com.blb.zycommunity.service.IZyOwnerService;
import com.blb.zycommunity.utils.JwtUtils;
import com.blb.zycommunity.utils.RsaUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@RestController
public class UniAppController {

    @Resource
    private IZyOwnerService zyOwnerService;

    @Autowired
    private BCryptPasswordEncoder bCryptPasswordEncoder;

    @PostMapping("/uni-app-login")
    public ResponseResult login(@RequestBody ZyOwner owner,
                                HttpServletRequest httpServletRequest,
                                HttpServletResponse httpServletResponse,
                                Authentication authentication) throws IOException {
        ZyOwner byNickname = zyOwnerService.findByNickname(owner.getOwnerNickname());
        if(byNickname!=null){
            String password = byNickname.getOwnerPassword();
            BCryptPasswordEncoder bc = new BCryptPasswordEncoder();
            boolean matches = bc.matches(owner.getOwnerPassword(),password);
            if(matches){
                //获取登录后的用户名
                if (owner == null) {
                    throw new RuntimeException("用户为空");
                }
                //将用户名转换为jwt token
                String token = JwtUtils.generateToken(owner.getOwnerNickname(), RsaUtils.privateKey, JwtUtils.EXPIRE_MINUTES);
                //将token发送给前端
                return ResponseResult.ok(token);
            }else{
                return ResponseResult.error(403L,"账号或密码错误");
            }
        }else {
            return ResponseResult.error(403L,"用户名不存在");
        }
    }
}
